<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Tornado," />




  


  <link rel="alternate" href="/atom.xml" title="理想-咸鱼" type="application/atom+xml" />






<meta name="description" content="tornado 源码之 StackContext（二） StackContext allows applications to maintain threadlocal-like statethat follows execution as it moves to other execution contexts. an exceptionhandler is a kind of stack-lo">
<meta property="og:type" content="article">
<meta property="og:title" content="tornado源码之StackContext（二）">
<meta property="og:url" content="http://yoursite.com/2018/12/21/tornado-yuan-ma-zhi-stackcontext%EF%BC%88-er-%EF%BC%89/index.html">
<meta property="og:site_name" content="理想-咸鱼">
<meta property="og:description" content="tornado 源码之 StackContext（二） StackContext allows applications to maintain threadlocal-like statethat follows execution as it moves to other execution contexts. an exceptionhandler is a kind of stack-lo">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-12-21T08:51:30.000Z">
<meta property="article:modified_time" content="2019-01-11T07:29:51.000Z">
<meta property="article:author" content="bigfish">
<meta property="article:tag" content="Tornado">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/12/21/tornado-yuan-ma-zhi-stackcontext（-er-）/"/>





  <title>tornado源码之StackContext（二） | 理想-咸鱼</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">理想-咸鱼</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">鱼翔浅底</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/21/tornado-yuan-ma-zhi-stackcontext%EF%BC%88-er-%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="bigfish">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="理想-咸鱼">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">tornado源码之StackContext（二）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-12-21T16:51:30+08:00">
                2018-12-21
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>  阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  4
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="tornado-源码之-StackContext（二）"><a href="#tornado-源码之-StackContext（二）" class="headerlink" title="tornado 源码之 StackContext（二）"></a>tornado 源码之 StackContext（二）</h1><blockquote>
<p>StackContext allows applications to maintain threadlocal-like state<br>that follows execution as it moves to other execution contexts.</p>
<p>an exception<br>handler is a kind of stack-local state and when that stack is suspended<br>and resumed in a new context that state needs to be preserved.</p>
<p>一个栈结构的上下文处理类<br>异常处理也是一个栈结构的上下文应用</p>
</blockquote>
<h2 id="contents"><a href="#contents" class="headerlink" title="contents"></a>contents</h2><ul>
<li><a href="#tornado-%E6%BA%90%E7%A0%81%E4%B9%8B-stackcontext%E4%BA%8C">tornado 源码之 StackContext（二）</a><ul>
<li><a href="#contents">contents</a></li>
<li><a href="#example-usage">example usage</a></li>
<li><a href="#head">head</a></li>
<li><a href="#state">_State</a></li>
<li><a href="#stackcontext">StackContext</a></li>
<li><a href="#exceptionstackcontext">ExceptionStackContext</a><ul>
<li><a href="#example">example</a></li>
</ul>
</li>
<li><a href="#nullcontext">NullContext</a></li>
<li><a href="#wrap">wrap</a></li>
<li><a href="#copyright">copyright</a></li>
</ul>
</li>
</ul>
<h2 id="example-usage"><a href="#example-usage" class="headerlink" title="example usage"></a>example usage</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@contextlib.contextmanager</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">die_on_error</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">yield</span></span><br><span class="line">    <span class="keyword">except</span>:</span><br><span class="line">        logging.error(<span class="string">"exception in asynchronous operation"</span>,exc_info=<span class="literal">True</span>)</span><br><span class="line">        sys.exit(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> StackContext(die_on_error):</span><br><span class="line">    <span class="comment"># Any exception thrown here *or in callback and its desendents*</span></span><br><span class="line">    <span class="comment"># will cause the process to exit instead of spinning endlessly</span></span><br><span class="line">    <span class="comment"># in the ioloop.</span></span><br><span class="line">    http_client.fetch(url, callback)</span><br><span class="line">ioloop.start()</span><br></pre></td></tr></table></figure>

<h2 id="head"><a href="#head" class="headerlink" title="head"></a>head</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> with_statement</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> contextlib</span><br><span class="line"><span class="keyword">import</span> functools</span><br><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="keyword">import</span> threading</span><br></pre></td></tr></table></figure>

<h2 id="State"><a href="#State" class="headerlink" title="_State"></a>_State</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_State</span><span class="params">(threading.local)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.contexts = ()</span><br><span class="line">_state = _State()</span><br></pre></td></tr></table></figure>

<h2 id="StackContext"><a href="#StackContext" class="headerlink" title="StackContext"></a>StackContext</h2><ol>
<li>初始化时保持传入的上下文对象</li>
<li>__enter__<ol>
<li>保存当前的全局上下文</li>
<li>append 新的上下文到全局上下文</li>
<li>构造新的上下文</li>
<li>进入新的上下文 __enter__</li>
</ol>
</li>
<li>__exit__<ol>
<li>调用新的上下文 context __exit__</li>
<li>回复全局上下文</li>
</ol>
</li>
</ol>
<p>全局上下文保存整个执行程序的上下文（栈）<br>with StackContext(context) 使程序包裹在 (global_context, context) 上执行<br>执行完成后恢复全局上下文</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StackContext</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, context_factory)</span>:</span></span><br><span class="line">        self.context_factory = context_factory</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.old_contexts = _state.contexts</span><br><span class="line">        _state.contexts = (self.old_contexts +</span><br><span class="line">                           ((StackContext, self.context_factory),))</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            self.context = self.context_factory()</span><br><span class="line">            self.context.__enter__()</span><br><span class="line">        <span class="keyword">except</span> Exception:</span><br><span class="line">            _state.contexts = self.old_contexts</span><br><span class="line">            <span class="keyword">raise</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">return</span> self.context.__exit__(type, value, traceback)</span><br><span class="line">        <span class="keyword">finally</span>:</span><br><span class="line">            _state.contexts = self.old_contexts</span><br></pre></td></tr></table></figure>

<h2 id="ExceptionStackContext"><a href="#ExceptionStackContext" class="headerlink" title="ExceptionStackContext"></a>ExceptionStackContext</h2><p>捕获上下文执行中抛出而又未被捕获的异常<br>作用类似 finally<br>用于执行在程序抛出异常后记录日志、关闭 socket 这些现场清理工作<br>如果 exception_handler 中返回 True, 表明异常已经被处理，不会再抛出</p>
<h3 id="example"><a href="#example" class="headerlink" title="example"></a>example</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> tornado <span class="keyword">import</span> ioloop</span><br><span class="line"><span class="keyword">import</span> tornado.stack_context</span><br><span class="line"><span class="keyword">import</span> contextlib</span><br><span class="line"></span><br><span class="line">ioloop = tornado.ioloop.IOLoop.instance()</span><br><span class="line"></span><br><span class="line"><span class="meta">@contextlib.contextmanager</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">context_without_catch</span><span class="params">()</span>:</span></span><br><span class="line">    print(<span class="string">"enter context"</span>)</span><br><span class="line">    <span class="keyword">yield</span></span><br><span class="line">    print(<span class="string">"exit context"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">exception_handler</span><span class="params">(type, value, traceback)</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">"catch uncaught exception:"</span>, type, value, traceback</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">with</span> tornado.stack_context.ExceptionStackContext(exception_handler):</span><br><span class="line">        <span class="keyword">with</span> tornado.stack_context.StackContext(context_without_catch):</span><br><span class="line">            <span class="keyword">print</span> <span class="number">0</span> / <span class="number">0</span></span><br><span class="line"></span><br><span class="line">main()</span><br><span class="line"><span class="comment"># enter context</span></span><br><span class="line"><span class="comment"># catch uncaught exception: &lt;type 'exceptions.ZeroDivisionError'&gt; integer division or modulo by zero &lt;traceback object at 0x0000000003321FC8&gt;</span></span><br></pre></td></tr></table></figure>

<p>__exit__ 中捕获 with 语句所包裹的程序执行中所抛出的异常，调用注册的 exception_handler 进行处理<br>exception_handler 返回 True，则异常不会蔓延</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExceptionStackContext</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, exception_handler)</span>:</span></span><br><span class="line">        self.exception_handler = exception_handler</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.old_contexts = _state.contexts</span><br><span class="line">        _state.contexts = (self.old_contexts +</span><br><span class="line">                           ((ExceptionStackContext, self.exception_handler),))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">if</span> type <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                <span class="keyword">return</span> self.exception_handler(type, value, traceback)</span><br><span class="line">        <span class="keyword">finally</span>:</span><br><span class="line">            _state.contexts = self.old_contexts</span><br></pre></td></tr></table></figure>

<h2 id="NullContext"><a href="#NullContext" class="headerlink" title="NullContext"></a>NullContext</h2><p>临时构造一个空的全局上下文</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NullContext</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.old_contexts = _state.contexts</span><br><span class="line">        _state.contexts = ()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, type, value, traceback)</span>:</span></span><br><span class="line">        _state.contexts = self.old_contexts</span><br></pre></td></tr></table></figure>

<h2 id="wrap"><a href="#wrap" class="headerlink" title="wrap"></a>wrap</h2><ol>
<li>比较当时的全局上下文（_state.contexts）和闭包中保存的上下文 (contexts)<ol>
<li>如果当前上下文长度长，表面执行环境需要重新构造</li>
<li>如果有两者有任何一个上下文不同，执行环境也要重新构造<ol>
<li>新建一个 NullContext(), 清除当前的_state.contexts(保存原来的，提出时复原)</li>
<li>以此为基础构造一个 contexts 上下文链</li>
</ol>
</li>
<li>如果 contexts 是 当前上下文的一个 prefix，则将当前上下文的后续部分作为上下文链，前面共有的无需再构造</li>
</ol>
</li>
<li>在新的上下文链（new_contexts）上执行 with 操作，保证 callback 的执行环境与当时保存时的一模一样</li>
</ol>
<p>之所以进行这样复杂的操作，是为了对某些前面执行环境相同的情况省略前面的构造，节省时间，否则，可以用一行代替：</p>
<p><code>new_contexts = ([NullContext()] + [cls(arg) for (cls,arg) in contexts])</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrap</span><span class="params">(fn)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> fn <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapped</span><span class="params">(callback, contexts, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="comment"># 函数实际调用时，上下文环境发生了变化，与`contexts = _state.contexts`已经有所不同</span></span><br><span class="line">        <span class="keyword">if</span> (len(_state.contexts) &gt; len(contexts) <span class="keyword">or</span></span><br><span class="line">            any(a[<span class="number">1</span>] <span class="keyword">is</span> <span class="keyword">not</span> b[<span class="number">1</span>]</span><br><span class="line">                <span class="keyword">for</span> a, b <span class="keyword">in</span> itertools.izip(_state.contexts, contexts))):</span><br><span class="line">            <span class="comment"># contexts have been removed or changed, so start over</span></span><br><span class="line">            new_contexts = ([NullContext()] +</span><br><span class="line">                            [cls(arg) <span class="keyword">for</span> (cls,arg) <span class="keyword">in</span> contexts])</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            new_contexts = [cls(arg)</span><br><span class="line">                            <span class="keyword">for</span> (cls, arg) <span class="keyword">in</span> contexts[len(_state.contexts):]]</span><br><span class="line">        <span class="keyword">if</span> len(new_contexts) &gt; <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">with</span> contextlib.nested(*new_contexts):</span><br><span class="line">                callback(*args, **kwargs)</span><br><span class="line">        <span class="keyword">elif</span> new_contexts:</span><br><span class="line">            <span class="keyword">with</span> new_contexts[<span class="number">0</span>]:</span><br><span class="line">                callback(*args, **kwargs)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            callback(*args, **kwargs)</span><br><span class="line">    <span class="keyword">if</span> getattr(fn, <span class="string">'stack_context_wrapped'</span>, <span class="literal">False</span>):</span><br><span class="line">        <span class="keyword">return</span> fn</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 保存上下文环境</span></span><br><span class="line">    contexts = _state.contexts</span><br><span class="line">    result = functools.partial(wrapped, fn, contexts)</span><br><span class="line">    result.stack_context_wrapped = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">return</span> result</span><br></pre></td></tr></table></figure>

<h2 id="copyright"><a href="#copyright" class="headerlink" title="copyright"></a>copyright</h2><p>author：bigfish<br>copyright: <a href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank" rel="noopener">许可协议 知识共享署名 - 非商业性使用 4.0 国际许可协议</a></p>
<hr>
<p>Sync From: <a href="https://github.com/TheBigFish/blog/issues/10" target="_blank" rel="noopener">https://github.com/TheBigFish/blog/issues/10</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Tornado/" rel="tag"># Tornado</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/21/-tornado-yuan-ma-zhi-stackcontext%EF%BC%88-yi-%EF%BC%89/" rel="next" title="tornado源码之StackContext（一）">
                <i class="fa fa-chevron-left"></i> tornado源码之StackContext（一）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/03/rust--an-zhuang-ji-pei-zhi/" rel="prev" title="rust 安装及配置">
                rust 安装及配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  
    <div id="gitalk-container"></div>
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">bigfish</p>
              <p class="site-description motion-element" itemprop="description">一些简单的想法</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#tornado-源码之-StackContext（二）"><span class="nav-number">1.</span> <span class="nav-text">tornado 源码之 StackContext（二）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#contents"><span class="nav-number">1.1.</span> <span class="nav-text">contents</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#example-usage"><span class="nav-number">1.2.</span> <span class="nav-text">example usage</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#head"><span class="nav-number">1.3.</span> <span class="nav-text">head</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#State"><span class="nav-number">1.4.</span> <span class="nav-text">_State</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#StackContext"><span class="nav-number">1.5.</span> <span class="nav-text">StackContext</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ExceptionStackContext"><span class="nav-number">1.6.</span> <span class="nav-text">ExceptionStackContext</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#example"><span class="nav-number">1.6.1.</span> <span class="nav-text">example</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NullContext"><span class="nav-number">1.7.</span> <span class="nav-text">NullContext</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#wrap"><span class="nav-number">1.8.</span> <span class="nav-text">wrap</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#copyright"><span class="nav-number">1.9.</span> <span class="nav-text">copyright</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bigfish</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.3</div>




<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  








  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <div id="gitalk-container"></div>
  <script type="text/javascript">
    var gitalk = new Gitalk({
      clientID: '539ee569f1e8cf3ea34a',
      clientSecret: 'd4384d3c96e794fea423f52d48aec0caab7d0eea',
      repo: 'blog_comment',
      owner: 'TheBigFish',
      admin: ['TheBigFish'],
      id: location.pathname,
      distractionFreeMode: 'false'
    })
    gitalk.render('gitalk-container')
  </script>



  





  

  

  

  

  

  

</body>
</html>
